package com.moly.websocketone.websocket;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Description:  原生的 websocket  基本 不需要配置
 * @Author: m01
 * @Date: created at  2018/11/10  21:06
 * @Modified By:
 */
@ServerEndpoint("/originalendpoint")
@Component
public class OriginalWebsocket {

    private Session session;
    private static CopyOnWriteArraySet<String> strings = null;
    private static int onlineCount = 0;



    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        changeOnlineCount(1);
        System.out.println("onlineCount  "+onlineCount);
        sendMessage(session,onlineCount);


    }

    @OnMessage(maxMessageSize=10L)
    public void onMessage(Session session,String message){

        System.out.println("收到信息 ["+session.getId()+"]   "+message);
        sendMessage(session,onlineCount);
    }
    @OnClose
    public void onClose(){
        System.out.println(this.session.getId()+" 断开连接");

        changeOnlineCount(-1);

    }
    @OnError
    public void onError(Session session,Throwable throwable){


    }

    private void  sendMessage(Session session,int n){
        try {
            session.getBasicRemote().sendText("在线人数"+n);
            System.out.println("发送信息  [" + session.getId() + "]" + n);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private  static synchronized void   changeOnlineCount(int n){
        onlineCount += n;
        if(onlineCount <0){
            onlineCount = 0;
        }
    }
}
